import { Hono } from 'hono';
import { logger } from 'hono/logger';
import { env } from 'hono/adapter';
import { proxy } from 'hono/proxy';

const app = new Hono();
app.use(logger());

app.get('/', c => {
  return c.text('Hello Hono!');
});

app.get('/api/version', c =>
  c.json({
    version: '0.11.6'
  })
);

app.get('/api/tags', async c => {
  try {
    const { OPENAI_BASE_URL, OPENAI_API_KEY } = env<{
      OPENAI_BASE_URL: string;
      OPENAI_API_KEY: string;
    }>(c);

    const data = await fetch(new URL(OPENAI_BASE_URL + '/models?type=text&sub_type=chat').href, {
      method: 'GET',

      
      headers: {
        Authorization: `Bearer ${OPENAI_API_KEY}`
      }
    });

    const json = await data.json();

    const models = [];
    for (const item of json.data) {
      models.push({
        name: item.id,
        model: item.id
      });
    }

    return c.json({
      models
    });
  } catch (error:any) {
    c.status(502);
    return c.json({
      error: error.message
    });
  }
});

app.post('/api/show', c => {
  const { CAPABILITIES } = env<{
    CAPABILITIES: string
  }>(c);

  let capabilities

  try {
    capabilities = JSON.parse(CAPABILITIES);
  } catch (error) {
    capabilities = null;
  }
  

  if (Array.isArray(capabilities)) {
    return c.json({
      model_info: { 'general.architecture': 'CausalLM' },
      capabilities: ['completion', ...capabilities]
    });
  }

  return c.json({
    model_info: { 'general.architecture': 'CausalLM' },
    capabilities: ['completion']
  });
});

app.post('/v1/chat/completions', async c => {
  const { OPENAI_BASE_URL, OPENAI_API_KEY } = env<{
    OPENAI_BASE_URL: string;
    OPENAI_API_KEY: string;
  }>(c);

  return proxy(new URL(OPENAI_BASE_URL + '/chat/completions').href, {
    ...c.req,
    headers: {
      ...c.req.header(),
      Authorization: `Bearer ${OPENAI_API_KEY}`
    }
  });
});

export default app;
